package com.probiz.estore.core.filter;

import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.AntPathMatcher;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.web.ServletCacheAdministrator;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.core.event.ConfigChangedEvent;
import com.probiz.estore.core.util.CacheUtil;
import com.probiz.estore.core.util.ContextUtil;
import com.probiz.estore.core.util.StringUtil;
import com.probiz.estore.product.service.ProdMainNtManager;
import com.probiz.estore.product.service.ProductManager;

public class PageCacheFilter extends
		com.opensymphony.oscache.web.filter.CacheFilter {

	private static final Log	logger	= LogFactory.getLog(PageCacheFilter.class);

	/**
	 * Only specified uris defined here will be cached. Note: we assume
	 * CacheFilter will take effect after The UrlRewriteFilter, so don't put the
	 * 'zh_CN' like context in uris.
	 */
	public String[]				cachableUris;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.oscache.web.filter.CacheFilter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig config) {
		// use customized initilization first to load out oscache.properties
		CacheUtil.getInstance().initOsCache(config.getServletContext());
		super.init(config);
		onConfigChanged(null);
	}

	/*
	 * 对每个匹配的Url判断是否可以进行缓存
	 * @see com.opensymphony.oscache.web.filter.CacheFilter#isCacheable(javax.servlet.ServletRequest)
	 */
	public boolean isCacheable(ServletRequest request) {
		boolean cachable = false;
		if (getTime() > 0) {
			/**
			 * 使用parameter cache=true可强制使用oscache的url cache
			 */
			AntPathMatcher antPathMatcher = new AntPathMatcher();
			if ("true".equals(request.getParameter("cache"))) {
				cachable = true;
			} else if (request.getParameter("noCache") == null && (request instanceof HttpServletRequest)) {
				HttpServletRequest req = (HttpServletRequest) request;
				if (!req.isRequestedSessionIdFromURL() && req.getMethod().equalsIgnoreCase("GET")) {
					///注意只对Get请求的才进行缓存
					for (int i = 0; i < cachableUris.length; i++) {
						//正则表达式匹配
						if(antPathMatcher.match(req.getContextPath()+cachableUris[i].trim(), req.getRequestURI())){
							cachable = true;  
							
							//----------------与业务相关方法 start:------------------
							if(antPathMatcher.match(req.getContextPath()+"/prod*/item*.html", req.getRequestURI())){
								doPageAction4ProductDetail(request);
							}
							
							//----------------与业务相关方法 end:------------------
							break;
						}
						
					}
				}
			}
		}
		return cachable;
	}
	
	/**
	 * 浏览商品详细页面时候的业务方法
	 * @param request
	 */
	private void doPageAction4ProductDetail(ServletRequest request) {
		//商品详细页面
		//start:记录点击率
		ProductManager productManager = (ProductManager)ContextUtil.getSpringBeanById("productManager");
		ProdMainNtManager prodMainNtManager = (ProdMainNtManager)ContextUtil.getSpringBeanById("prodMainNtManager");
		Integer productId = productManager.getProductIdByUri(((HttpServletRequest)request).getRequestURI());
		Product product = productManager.getById(productId);
		if(product != null &&  Product.STATUS_ACTIVE.equals(product.getStatus())){
			//确保商品激活
			prodMainNtManager.doRecordViewCount(productId, ((HttpServletRequest)request).getSession());
		}
		//end:  记录点击率
	}
	
	/**
	 * 覆盖基类方法，加入组
	 */
	public String[] createCacheGroups(HttpServletRequest httpRequest, ServletCacheAdministrator scAdmin, Cache cache) {
		AntPathMatcher antPathMatcher = new AntPathMatcher();
		if(antPathMatcher.match(httpRequest.getContextPath()+"/prod*/item*.html", httpRequest.getRequestURI())){
			ProductManager productManager = (ProductManager)ContextUtil.getSpringBeanById("productManager");
			Integer productId = productManager.getProductIdByUri(httpRequest.getRequestURI());
			if(null != productId){
				//如果是商品详细页，则加入商品组。
				return new String[]{
						CacheUtil.OSCACHE_PRODUCT_GROUP_PREFIX + productId.toString()
				};
			}
		}
        return null;
    }
	

	public void onConfigChanged(ConfigChangedEvent event) {
		logger.warn("Updating server side page cache time settings from: "
				+ getTime() + " to: "
				+ ConfigUtil.getInstance().getServerSidePageCacheSeconds());
		setTime(ConfigUtil.getInstance().getServerSidePageCacheSeconds());
		logger.info("Enable server side page caching? " + (getTime() > 0));


		logger.warn("Updating cachable urls: "
				+ ConfigUtil.getInstance().getCachableUrls());
		cachableUris = StringUtil.toArrayByDel(ConfigUtil.getInstance()
				.getCachableUrls(), ",");

	}
}
